const express = require("express");
const svgCaptcha = require('svg-captcha');

const ManagerModel = require('../../model/managerModel');
const md5 = require('md5')
var router = express.Router()

router.get("/", async(req, res) => {
    // res.render('admin/login/login.html')
    // const result = new ManagerModel({
    //     username: 'admin',
    //     password: md5('123456')
    // })
    // await result.save()
    res.send("用户登录页面")
})
router.get('/captcha', function(req, res) {
    var captcha = svgCaptcha.create();
    req.session.captcha = captcha.text;

    res.type('svg');
    res.status(200).send(captcha.data);
});
//推出登录
router.get('/loginOut', function(req, res) {
    req.session.userinfo = "";
    res.redirect('/admin/login')
});

router.get("/doLogin", (req, res) => {
    const { username, password, verify } = res.body
        // 1,判读验证码是否正确
    if (verify.toLocaleLowerCase() != res.session.captcha.toLocaleLowerCase()) {
        res.send('验证码错误!')
        res.render('admin/public/error.html', {
            'redirectUrl': '/admin/login',
            'message': '图形验证码错误！'
        })
        return
    }

    // 2、判读用户名密码是否合法
    ManagerModel.find({ "username": username, "password": md5(password) }, (err, docs) => {
        if (err) {
            console.log(err);
            res.render('admin/public/success.html', {
                'redirectUrl': '/admin/login',
                'message': '用户名或者密码错误！'
            })
            return
        }
        // 保存到session
        req.session.userInfo = docs[0]
        res.render('admin/public/success.html', {
            'redirectUrl': '/admin',
            'message': '登录成功！'
        })
    })

    // res.send("执行登录")
})

module.exports = router